package com.demo.service.impl;

import com.demo.common.model.BaseQuery;
import com.demo.common.utils.AuthUtils;
import com.demo.entity.Customer;
import com.demo.mapper.CustomerMapper;
import com.demo.vo.ClueVo;
import com.demo.vo.PieData;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.mapper.ClueMapper;
import com.demo.entity.Clue;
import com.demo.service.ClueService;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService {
    @Autowired
    private ClueMapper clueMapper;
    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public PageInfo<ClueVo> queryClueByPage(Integer current, Integer pageSize) {
        PageHelper.startPage(current, pageSize);
        List<ClueVo> list = clueMapper.selectClueList(new BaseQuery());
        return new PageInfo<>(list);
    }

    @Override
    public boolean save(Clue clue) {
        clue.setOwnerId(AuthUtils.getLoginUserId());
        clue.setCreateBy(AuthUtils.getLoginUserId());
        clue.setCreateTime(new Date());
        int result = clueMapper.insert(clue);
        return result > 0;
    }

    @Override
    public boolean updateById(Clue clue) {
        clue.setEditTime(new Date());
        clue.setEditBy(AuthUtils.getLoginUserId());
        int result = clueMapper.updateById(clue);
        return result > 0;
    }

    @Override
    public ClueVo queryClueDetailInfoById(Integer id) {

        return clueMapper.queryClueDetailInfo(id);
    }

    @Override
    public List<PieData> queryNoteWayList() {
        List<PieData> list = clueMapper.selectNoteWayList();
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)  // 添加事务
    public Boolean transformToCustomer(Integer clueId) {
        // 1、修改线索转态为“已转换客户”
        Clue clue = new Clue();
        clue.setId(clueId);
        clue.setState(-1);
        clue.setEditBy(AuthUtils.getLoginUserId());
        clue.setEditTime(new Date());
        int result = clueMapper.updateById(clue);
        if (result > 0) {
            // 根据表示查询线索信息
            Clue  clueInfo = clueMapper.selectById(clueId);
            //2、新增客户记录
            Customer customer = new Customer();
            customer.setClueId(clueId);
            clue.setCreateBy(AuthUtils.getLoginUserId());
            clue.setCreateTime(new Date());
            clue.setIntentionProduct(clueInfo.getIntentionProduct());
            customerMapper.insert(customer);
        }
        return result > 0;
    }
}
